package handler

import (
	"context"
	"github.com/golang/protobuf/ptypes/empty"
	"github.com/golang/protobuf/ptypes/timestamp"
	"kop/libs/database"
	"kop/modules/server/entity"
	"kop/modules/server/models"
	"kop/pb/service"
	"time"
)

type ServerServiceHandler struct {
}

func (h *ServerServiceHandler) GetServers(_ context.Context, _ *empty.Empty, resp *service.Servers) error {

	var data = models.GetServers()

	resp.Servers = make([]*service.Server, 0, len(data))
	for _, v := range data {
		resp.Servers = append(resp.Servers, &service.Server{
			ServerID:  v.ServerID,
			Name:      v.Name,
			Address:   v.Address,
			Timestamp: &timestamp.Timestamp{Seconds: v.OpenTime.Unix()},
		})
	}

	return nil
}

func (h *ServerServiceHandler) Create(_ context.Context, server *service.Server, _ *empty.Empty) error {

	return database.DB.Create(&entity.Server{ServerID: server.ServerID, Name: server.Name, Address: server.Address, State: entity.StatusNormal, OpenTime: time.Unix(server.Timestamp.Seconds, 0)}).Error
}
